package server

import (
	"fmt"
	"net/http"
	"time"

	"log"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var (
	ch chan struct{}
	upgrader = &websocket.Upgrader {
		HandshakeTimeout: 10 * time.Second,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

func Start(port int) {
	ch := make(chan struct{}, 1)

	engine := gin.Default()
	gin.SetMode(gin.DebugMode)
	
	engine.StaticFS("/static", http.Dir(getCurDir() + "/static"))
	SetRoute(engine)

	server := &http.Server{
		Addr: fmt.Sprintf(":%d", port),
		Handler: engine,
	}
	go func ()  {
		server.ListenAndServe()
		log.Println("web server started")

		<- ch
		server.Close()
	} () 
}

func Close() {
	close(ch)
	fmt.Println("server closed")
}

func getCurDir() string {
	dir, _ := os.Getwd()
	return dir 
}